/**
 * Title UserManageController
 * Package com.sba.manage.controller
 * Copyright 2024 www.hundsun.com All Rights Reserved.
 *
 * @author zhanggd1816@hundsun.com
 * @date 2024/4/26 6:59 PM
 * @version V5.1.2
 */
package com.ruoyi.manage.controller;

import com.ruoyi.common.app.core.RespEntity;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.TokenUtils;
import com.ruoyi.manage.bean.AppleLoginVO;
import com.ruoyi.manage.db.model.SbaUsers;
import com.ruoyi.manage.service.IAppleLogin;
import com.ruoyi.manage.service.IUserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

/**
 * 用户管理
 * ClassName UserManageController
 *
 * @author gd
 * @date 2024/4/26 6:59 PM
 */
@Controller
public class AppUserManageController extends AppBaseController {

    @Autowired
    private IUserManager userManager;

    @Autowired
    private IAppleLogin appleLoginService;

    /**
     * 登录或者注册
     * @param appleLoginVO 苹果请求实体
     * @return 响应实体
     */
    @PostMapping("/app/user/login")
    @ResponseBody
    public RespEntity loginOrRegiter(@RequestBody AppleLoginVO appleLoginVO) {

        if (!appleLoginService.verify(appleLoginVO)) {
            //登录失败
//            return RespEntity.fail("登陆验证失败");
        }
        //登录成功
        SbaUsers users = new SbaUsers();
        String appid = appleLoginVO.getUserID();
        if (StringUtils.isEmpty(appid)) {
            return RespEntity.fail("appOpenId为空");
        }
        if (StringUtils.isNoneBlank(appid)) {
            users.setAppleOpenId(appid);
        }
        try {
            //查询用户是否存在
            long i = userManager.count(users);
            String token = TokenUtils.generateToken(appid);
            if (i > 0) {
                //用户存在，登录成功
                //查询用户信息，返回前端
                SbaUsers respUser = userManager.queryByUsers(users);
                //更新用户登录时间和 token
                updateUser(appid, appleLoginVO.getEmail(), appleLoginVO.getFullName());
                respUser.setPasswordHash(null);
                return RespEntity.ok(token, respUser);
            }
            //用户不存在，需要注册
            users.setUsername(appleLoginVO.getFullName());
            users.setEmail(appleLoginVO.getEmail());
            SbaUsers respUser = userManager.register(users);
            if (null == respUser) {
                return RespEntity.fail("用户注册失败");
            }
            //更新用户登录时间
            updateUser(appid, null, null);
            respUser.setPasswordHash(null);
            return RespEntity.ok(token, respUser);
        } catch (Exception e) {
            logger.error("登录异常", e);
            return RespEntity.fail("登录异常");
        }
    }

    private void updateUser(String appid, String email, String fullName) {
        //更新用户登录时间和 token
        SbaUsers upUser = new SbaUsers();
        upUser.setLastLoginDate(new Date());
        if (StringUtils.isNotBlank(email)) {
            upUser.setEmail(email);
        }
        if (StringUtils.isNotBlank(fullName)) {
            upUser.setUsername(fullName);
        }
        SbaUsers quUser = new SbaUsers();
        quUser.setUserId(appid);
        userManager.updateByUsers(quUser, upUser);
    }
}